package main

import (
	"google.golang.org/grpc"
	qy "gitee.com/go_rpc_echo/qiye"
	"golang.org/x/net/context"
	"net"
	"log"
	"github.com/gomodule/redigo/redis"
	"encoding/json"
	ut "gitee.com/go_rpc_echo/util"
	"bytes"
	"mime/multipart"
	"net/http"
	"io/ioutil"
	"io"
	"fmt"
)


type QiyeRpcServer struct {

}

func (this *QiyeRpcServer)GetAccessToken(ctx context.Context, qiye *qy.QiyeInfo) (*qy.QiyeAccessToken,error){
	log.Println("GetAccessToken")

	t:=qy.QiyeAccessToken{}
	redis_conn, _ := redis.Dial("tcp", "127.0.0.1:6379")
	defer redis_conn.Close()
	exists, _ := redis.Bool(redis_conn.Do("EXISTS", "qiye_alarm_access_token"))
	if exists{
		t.AccessToken,_ = redis.String(redis_conn.Do("GET", "qiye_alarm_access_token"))
		i,_ := redis.Int64(redis_conn.Do("PTTL", "qiye_alarm_access_token"))
		t.ExpiresIn = i/1000
	}else{
		s:=ut.CurlGet("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+qiye.Corpid+"&corpsecret="+qiye.Corpalarmsecret)
		json.Unmarshal([]byte(s),&t)
		redis_conn.Do("SET", "qiye_alarm_access_token", t.AccessToken)
		redis_conn.Do("EXPIRE", "qiye_alarm_access_token", t.ExpiresIn)
	}
	return &t,nil
}
func (this *QiyeRpcServer)SendText(ctx context.Context,req *qy.SendTextRequest)(*qy.SendTextResponse,error){
	log.Println("SendText")

	access_token,_ := this.GetAccessToken(ctx,req.Qi)
	url:="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+access_token.AccessToken
	ut.PostJson(`
{
   "touser" : "@all",
   "msgtype" : "text",
   "agentid" : 1000002,
   "text" : {
       "content" : "`+req.Text+`"
   },
   "safe":0
}
`,url)
	return &qy.SendTextResponse{Issend:true},nil
}


func (this *QiyeRpcServer) SendPic(ctx context.Context,req *qy.SendTextRequest)(*qy.SendTextResponse,error){
	at,_ :=this.GetAccessToken(ctx , req.Qi)


	// 创建表单文件
	// CreateFormFile 用来创建表单，第一个参数是字段名，第二个参数是文件名
	buf := new(bytes.Buffer)
	writer := multipart.NewWriter(buf)
	formFile, err := writer.CreateFormFile("media", "tmp.jpg")
	if err != nil {
		log.Fatalf("Create form file failed: %s\n", err)
	}
	imagPath := req.Text
	resp, _ := http.Get(imagPath)
	body, _ := ioutil.ReadAll(resp.Body)
	io.Copy(formFile, bytes.NewReader(body))
	if err != nil {
		log.Fatalf("Write to form file falied: %s\n", err)
	}
	// 发送表单
	contentType := writer.FormDataContentType()
	writer.Close() // 发送之前必须调用Close()以写入结尾行
	url := "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token="+at.AccessToken+"&type=image"

	res, err := http.Post(url, contentType, buf)
	if err != nil {
		log.Fatalf("Post failed: %s\n", err)
	}

	defer res.Body.Close()
	body, _ = ioutil.ReadAll(res.Body)

	fmt.Println(res)

	media:= struct {
		MediaId string `json:"media_id"`
	}{}
	json.Unmarshal(body,&media)
	fmt.Println(string(body))
	url="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+at.AccessToken
	log.Printf(ut.PostJson(`
{
   "touser" : "@all",
   "msgtype" : "image",
   "agentid" : 1000002,
   "image" : {
       "media_id" : "`+media.MediaId+`"
   },
   "safe":0
}
`,url))
	return &qy.SendTextResponse{Issend:true},nil
}

func main()  {
	grpcServer := grpc.NewServer()
	qy.RegisterQiyeRpcServer(grpcServer,&QiyeRpcServer{})
	lis, err := net.Listen("tcp", "0.0.0.0:10005")
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	grpcServer.Serve(lis)
}
